import React, { Component } from 'react'
import { Form, Input,Button, Card, Table, Modal, message} from 'antd'
import {reqAddCategory, reqCategoryList, reqUpdateCategory} from '../../api/index'
import {PlusCircleOutlined} from'@ant-design/icons'

export default class Category extends Component {
  state = {
    isModalVisible: false,
    categoryList: [],
    openType: '',
    currentValue: {},
    pageSize: 5
  }
  formRef = React.createRef()
  columns = [
    {
      title: 'ID',
      dataIndex: '_id',
      key: 'id'
    },
    {
      title: '分类名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '操作',
      key: 'options',
      render: (value) => {
        return <Button onClick={()=>this.showUpdate(value)} type="link">修改</Button>
      },
      width: '20%'
    },
  ]


  handleOk = async () => {
    const {openType} = this.state
    const {parentId,categoryName} = this.formRef.current.getFieldValue()
    const {_id} = this.state.currentValue
    console.log(this.state.currentValue);
    if (openType === '新增分类') {
      await reqAddCategory(parentId, categoryName)
    } else if (openType === '修改分类') {
      const res = await reqUpdateCategory(_id, categoryName)
      console.log(res);
      if (res.data.status !== 0) {
        return message.error(res.data.msg)
      } else {
        message.success('修改成功！')
      }
    }
    this.getCategoryList()
    this.formRef.current.resetFields();
    this.setState({isModalVisible: false})
  }
  showAdd = () => {
    this.setState({isModalVisible: true, openType: '新增分类'})
  }
  showUpdate = (value) => {
    console.log(value.name);
    this.setState({isModalVisible: true, openType: '修改分类', currentValue: value})
  }
  handleCancel = () => {
    this.setState({isModalVisible: false})
  }
  getCategoryList = async () => {
    const res = await reqCategoryList()
    let {status, data} = res.data
    if (status === 0) {
      this.setState({categoryList: data})
    } else {
      message.error(data.msg)
    }
  }
  onFinish = (values) => {
    console.log('Success:', values);
  }
  handleSizeChange = (_, newSize) => {
    this.setState({pageSize: newSize})
  }
  componentDidMount() {
    this.getCategoryList()
  }

  render() {
    let {isModalVisible} = this.state
    return (
      <div>
        <Card extra=
          {
            <Button type="primary" onClick={this.showAdd}>
              <PlusCircleOutlined />创建品类
            </Button>
          }
        >
        <Table pagination={{pageSize:this.state.pageSize,showSizeChanger:true, showQuickJumper:true, onShowSizeChange: this.handleSizeChange, pageSizeOptions: [5,10,15,20]}} bordered dataSource={this.state.categoryList} columns={this.columns}>
        {/* <Pagination size="small" total={50} showSizeChanger showQuickJumper /> */}
        </Table>
        </Card>
        {/* 解决antd4回显的问题 每次重新挂载modal使得initialValue可以更新 */}
        {
          this.state.isModalVisible &&
          <Modal
            title={this.state.openType}
            visible={isModalVisible}
            onOk={this.handleOk}
            onCancel={this.handleCancel}
            okText="确定"
            cancelText="取消"
          >
          <Form
            name="basic"
            ref={this.formRef}
            // initialValues={
            //   this.state.openType==='新增分类'? {categoryName: ''}: {categoryName: this.state.currentValue}
            // }
          >
            <Form.Item
              label="父级分类"
              name="parentId"
            >
              <Input />
            </Form.Item>
            <Form.Item
              label="分类名称"
              name="categoryName"
              rules={[{ required: true, message: '请输入分类名称' }]}
            >
              <Input placeholder="请输入分类名称" defaultValue={this.state.currentValue.name}/>
            </Form.Item>
          </Form>
        </Modal>
        }

      </div>
    )
  }
}
